package com.bicon.botu.mall.component.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bicon.botu.mall.component.common.SearchConstants;
import com.bicon.botu.mall.component.entity.HistorySearch;
import com.bicon.botu.mall.component.entity.SearchStatistics;
import com.bicon.botu.mall.component.mapper.HistorySearchMapper;
import com.bicon.botu.mall.component.service.IHistorySearchService;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.common.utils.JsonUtil;
import com.bicon.botu.core.base.repository.redis.RedisHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 搜索历史表 服务实现类
 *
 * @author 张凡
 * @date 2017/7/19 下午 14:49
 */
@Service
@Transactional
public class HistorySearchServiceImpl extends ServiceImpl<HistorySearchMapper, HistorySearch> implements IHistorySearchService {
    @Autowired
    RedisHandler redisHandler;
    @Autowired
    HistorySearchMapper historySearchMapper;

    /**
     * 添加搜索记录
     *
     * @param userId     用户id
     * @param searchWord 搜索关键字
     * @return
     */
    @Override
    public BaseResult add(String userId, String type, String searchWord, Integer total) {
        //查询数据库是否已搜过此搜索词
        HistorySearch historyWord = new HistorySearch().selectOne(new EntityWrapper<HistorySearch>().eq("type", type)
                .eq("search_word", searchWord).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        boolean result;
        //若不存在则新增搜索词,次数为1
        if (historyWord == null) {
            HistorySearch historySearch = new HistorySearch();
            historySearch.setUserId(userId);
            historySearch.setSearchWord(searchWord);
            historySearch.setType(type);
            historySearch.setSearchTimes(1);
            historySearch.preInsert();
            result = historySearch.insert();
        } else {
            //若存在则修改搜索次数（次数+1）
            historyWord.setSearchTimes(historyWord.getSearchTimes() + 1);
            historyWord.preUpdate();
            result = historyWord.updateById();
        }
        if (!result) {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
        this.initHistorySearchToRedis(userId, type);
        //增加统计表数据
        SearchStatistics statistics = new SearchStatistics().selectOne(new EntityWrapper<SearchStatistics>().eq("search_word", searchWord).eq("type", type));
        if (statistics == null) {
            SearchStatistics searchStatistics = new SearchStatistics();
            searchStatistics.setType(type);
            searchStatistics.setSearchWord(searchWord);
            searchStatistics.setSumSearchTimes(1);
            searchStatistics.setDaySearchTimes(1);
            searchStatistics.setWeekSearchTimes(1);
            searchStatistics.setMonthSearchTimes(1);
            searchStatistics.setResultNum(total);
            searchStatistics.preInsert();
            result = searchStatistics.insert();
        } else {
            statistics.setSumSearchTimes(statistics.getSumSearchTimes() + 1);
            statistics.setDaySearchTimes(statistics.getDaySearchTimes() + 1);
            statistics.setWeekSearchTimes(statistics.getWeekSearchTimes() + 1);
            statistics.setMonthSearchTimes(statistics.getMonthSearchTimes() + 1);
            statistics.setResultNum(total);
            result = statistics.updateById();
        }
        if (!result) {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 逻辑删除用户搜索记录(单条)
     *
     * @param id     搜索词id
     * @return
     */
    @Override
    public BaseResult deleteOneHistory(String id) {
        //判断数据库是否有此搜索词
        HistorySearch historySearch = new HistorySearch().selectById(id);
        if (historySearch == null) {
            return new BaseResult(Constants.RESPONSE_CODE_602, Constants.RESPONSE_MESSAGE_602);
        }
        //逻辑删除搜索词
        historySearch.setLogicDelete(Constants.DEL_LOGIC_DELETE);
        historySearch.preUpdate();
        boolean result = historySearch.updateById();
        if (!result) {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
        this.initHistorySearchToRedis(historySearch.getUserId(), historySearch.getType());
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 逻辑清空用户搜索记录
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public BaseResult deleteAllHistory(String type,String userId) {
        List<HistorySearch> historySearches = new HistorySearch().selectList(new EntityWrapper<HistorySearch>()
                .eq("user_id", userId).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        if (historySearches == null) {
            return new BaseResult(Constants.RESPONSE_CODE_602, Constants.RESPONSE_MESSAGE_602);
        }
        Boolean result = updateBatchById(historySearches);
        if (!result) {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
        this.initHistorySearchToRedis(userId, type);
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 查询一周内搜索次数最多的几个词
     *
     * @param num 词的数量
     * @return
     */
    @Override
    public List<String> mostSearchedWords(String type, Integer num) {
        List<String> words = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("num", num);
        map.put("type", type);
        List<HistorySearch> historySearchList = historySearchMapper.mostSearchedWords(map);
        for (HistorySearch historySearch : historySearchList) {
            words.add(historySearch.getSearchWord());
        }
        return words;
    }

    /**
     * 初始化用户的最新20条记录历史搜索到redis
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public BaseResult initHistorySearchToRedis(String userId, String type) {
        //清空此用户的redis
        redisHandler.getGlobalRedisTemplate().remove(SearchConstants.HISTORY_SEARCH_KEY, type + ":" + userId);
        //查询出所有的正常状态的用户历史搜索记录
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
        List<HistorySearch> historySearches = historySearchMapper.findUserSearchHistory(map);
        //保存到redis上
        List<String> stringList=new ArrayList<>();
        for(HistorySearch historySearch:historySearches){
            stringList.add(JsonUtil.toJson(historySearch));
        }
        if(stringList != null && stringList.size() > 0){
            redisHandler.getGlobalRedisTemplate().cacheList(SearchConstants.HISTORY_SEARCH_KEY, type+":"+userId, stringList);
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 获取用户的历史搜索详情
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public List<HistorySearch> getHistorySearchDetailFromRedis(String userId, String type) {
        //从redis上获取用户的全部搜索历史记录
        List<String> list = redisHandler.getLocalRedisTemplate().getList(SearchConstants.HISTORY_SEARCH_KEY,type+":"+userId);
        List<HistorySearch> historySearchList = new ArrayList<>();
        for(String str:list){
            HistorySearch historySearch=JsonUtil.fromJson(str,HistorySearch.class);
            historySearchList.add(historySearch);
        }
        return historySearchList;
    }
}
